package com.example.rocketmq.service.impl;

import com.example.rocketmq.service.OrderFeignService;
import com.situ.model.Order;
import com.situ.utils.JsonResult;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 消费者
 * 处理秒杀订单
 *
 * @author: CHT
 * create: 2025-9-18
 */
@Service
@RocketMQMessageListener(topic = "skymall-orders", consumerGroup = "seckill-order-consumer-group")
public class OrderConsumeServiceImpl implements RocketMQListener<Order> {

    private RedisTemplate<String, Object> redisTemplate;
    private OrderFeignService orderFeignService;
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    public void setRocketMQTemplate(RocketMQTemplate rocketMQTemplate) {
        this.rocketMQTemplate = rocketMQTemplate;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setOrderFeignService(OrderFeignService orderFeignService) {
        this.orderFeignService = orderFeignService;
    }


    //见听到消息队列的消息,开始消费
    @Override
    public void onMessage(Order order) {
        Integer seckillProductId = order.getOrderItems().getFirst().getProductId();

        // 创建订单,扣除库存
        try {
            ResponseEntity<JsonResult<Order>> re = orderFeignService.createSeckillOrder(order);
            JsonResult<?> jsonResult = re.getBody();
            if (jsonResult != null && jsonResult.isSuccess()) {
                Order  order1 = (Order) jsonResult.getData();
                Integer orderId=order1.getId();// 订单主键


                redisTemplate.opsForValue().set("seckil-order:" + order.getSeckillNo(), true, Duration.ofMinutes(10));


                //延迟消息，5分钟后查询订单是否支持
              //  this.rocketMQTemplate.syncSendDelayTimeSeconds("shoplook2005-orders-check", orderId, 2 * 60);

            } else {
                // 业务处理失败，记录日志但不重试
                Logger logger = LoggerFactory.getLogger(OrderConsumeServiceImpl.class);
                logger.error("创建秒杀订单业务失败，订单信息: {}, 返回结果: {}", order, jsonResult);
                redisTemplate.opsForValue().set("seckil-order:" + order.getSeckillNo(), false, Duration.ofMinutes(10));
                redisTemplate.opsForValue().increment("seckill-stock:" + seckillProductId, 1);
                // 不抛出异常，避免重试
                return;
            }
        } catch (Exception e) {
            Logger logger = LoggerFactory.getLogger(OrderConsumeServiceImpl.class);
            logger.error("订单秒杀失败，订单信息: {}", order, e);

            // 设置此秒杀商品订单失败
            redisTemplate.opsForValue().set("seckil-order:" + order.getSeckillNo(), false, Duration.ofMinutes(10));
            // redis中秒杀商品数量回滚
            redisTemplate.opsForValue().increment("seckill-stock:" + seckillProductId, 1);

            throw new RuntimeException("订单秒杀失败", e);
        }
    }
}
